import React, {useReducer, useContext} from "react";

const reducer = (preState, action) => {
    console.log(preState, action);

    const newState = {...preState};
    if (action.type === "update_A") {
        newState.a = action.value;
    } else if (action.type === "update_B") {
        newState.b = action.value;
    }
    return newState;
}

const initialState = {
    a: "1111111",
    b: "2222222",
}

// 定义GlobalContext将state和dispatch分发给子组件
const GlobalContext = React.createContext();
export default function App() {

    const [state, dispatch] = useReducer(reducer, initialState);

    return <GlobalContext.Provider value={{ state, dispatch }}>
        <div>
            <Child1/>
            <Child2/>
            <Child3/>
        </div>
    </GlobalContext.Provider>
}

function Child1() {
    // 获取dispatch来修改state
    const {dispatch} = useContext(GlobalContext);

    return <div>
        <button onClick={() => dispatch({type: "update_A", value: "333333333"})}>修改a的值</button>
        <button onClick={() => dispatch({type: "update_B", value: "444444444"})}>修改b的值</button>
    </div>;
}

function Child2() {
    // 获取state来显示数据
    const {state} = useContext(GlobalContext);
    return <div>
        {state.a}
    </div>
}

function Child3() {
    // 获取state来显示数据
    const {state} = useContext(GlobalContext);
    return <div>
        {state.b}
    </div>
}